package com.gitee.wsl.ext.array.bytes

import com.gitee.wsl.ext.array.IntArray
import com.gitee.wsl.lang.ByteOrder


@OptIn(ExperimentalUnsignedTypes::class)
fun UByteArray.toIntArray(): IntArray =
    map { it.toInt() }.toIntArray()

@OptIn(ExperimentalUnsignedTypes::class)
fun IntArray.toUByteArray(): UByteArray =
    map { it.toUByte() }.toUByteArray()


/**
 * Converts the given byte array into an int array via big-endian conversion (4 bytes become 1 int).
 * @throws IllegalArgumentException if the byte array size is not a multiple of 4.
 */
fun ByteArray.toIntArray(byteOrder: ByteOrder = ByteOrder.BigEndian): IntArray {
    if (this.size % 4 != 0) {
        throw IllegalArgumentException("Byte array length must be a multiple of 4")
    }
    val array = IntArray(this.size / 4)
    for (i in array.indices) {
        //val integer = arrayOf(this[i* 4], this[i* 4 + 1], this[i* 4 + 2], this[i* 4 + 3])
        //array[i] = integer.toInt()
        array[i] = toInt(byteOrder, startIndex = i* 4)
    }
    return array
}

/**
 * Converts the given int array into a byte array via big-endian conversion
 * (1 int becomes 4 bytes).
 * @return The converted array.
 */
fun IntArray.toByteArray(byteOrder: ByteOrder = ByteOrder.BigEndian): ByteArray {
    val array = ByteArray(this.size * 4)
//    for (i in this.indices) {
//        val bytes = this[i].toByteArray(byteOrder)
//        array[i * 4] = bytes[0]
//        array[i * 4 + 1] = bytes[1]
//        array[i * 4 + 2] = bytes[2]
//        array[i * 4 + 3] = bytes[3]
//    }
    toByteArray(array,byteOrder)
    return array
}

fun IntArray.toByteArray(array:ByteArray,
                         byteOrder: ByteOrder = ByteOrder.BigEndian,
                         startIndex:Int = 0
) {
    for (i in this.indices) {
        this[i].toByteArray(array, byteOrder, startIndex = startIndex+i*4)
    }
}